package com.cqndt.disaster.device.common.exception;

import com.cqndt.disaster.device.common.util.PrintUtil;
import com.cqndt.disaster.device.common.util.Result;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理器
 */
@ControllerAdvice
public class RRExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(DuplicateKeyException.class)
	public Result handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return new Result().failure(-1,"数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public void handleAuthorizationException(AuthorizationException e, HttpServletRequest httpRequest, HttpServletResponse httpResponse){
		logger.error(e.getMessage(), e);
		PrintUtil.printJson(httpRequest,httpResponse, -4,"没有权限，请联系管理员授权");
	}
	@ExceptionHandler(UnauthorizedException.class)
	public void handleUnauthorizedException(UnauthorizedException e, HttpServletRequest httpRequest, HttpServletResponse httpResponse){
		logger.error(e.getMessage(), e);
		PrintUtil.printJson(httpRequest,httpResponse, -4,"没有权限，请联系管理员授权");
	}

	@ExceptionHandler(Exception.class)
	public Result handleException(Exception e){
		logger.error(e.getMessage(), e);
		return new Result().failure(-1,e.getMessage());
	}
}
